import {
  addContent,
  addEntry,
  addResumeDetail,
  delContent,
  delEntry,
  editContent,
  editEntry,
  editSectionName,
  getResumeDetail,
  sortEntry,
  toggleHideEntry,
  updatePersonalDetail,
} from "@/service";
import { useCommonStore } from "@/src/providers/common-store-provider";
import { useContentStore } from "@/src/providers/content-store-provider";
import { useCustomizationStore } from "@/src/providers/customization-store-provider";
import { usePersonalDetailStore } from "@/src/providers/personal-detail-store-provider";
import { produce } from "immer";
import cookie from "js-cookie";
import { useRouter } from "next/navigation";

function needLogin() {
  const token = cookie.get("baijie_token");
  const id = new URLSearchParams(location.search).get("id");
  if (!token && !id) {
    return false;
  }
  return true;
}
const Index = () => {
  const {
    content,
    update: updateContent,
    updateSection,
    deleteContent,
  } = useContentStore((state) => state);
  const router = useRouter();

  const { customization, update: updateCustomization } = useCustomizationStore(
    (state) => state
  );
  const { personalDetails, update: updatePersonalDetails } =
    usePersonalDetailStore((state) => state);
  const { setCurrentTab, setShowLogin, setIsLogin, isMobile } = useCommonStore(
    (state) => state
  );
  const goback = (url?) => {
    if (isMobile) {
      if (url) {
        router.replace(url);
      } else {
        router.back();
      }
    } else {
      setCurrentTab("content");
    }
  };
  const saveAll = async () => {
    const resume = {
      content: Object.values(content),
      customization,
      personalDetails,
    };
    // delete resume.customization.defaultSectionOrder
    const res = await addResumeDetail(resume);
    if (res?.code === 200) {
      const data = await getResumeDetail({ id: res.data });
      const { content, customization, personalDetails } = data.data;
      updateContent(content);
      updateCustomization(customization);
      updatePersonalDetails(personalDetails);
      if (isMobile) {
        const newUrl = `/content?id=${res.data}`;
        goback(newUrl);
      } else {
        const newUrl = `${window.location.pathname}?id=${res.data}`;
        window.history.replaceState({}, "title", newUrl);
        setCurrentTab("content");
        return res;
      }
    }
    if (res?.code === 401) {
      setShowLogin(true);
      setIsLogin(false);
      return;
    }
  };
  const save = async (data) => {
    if (personalDetails.id) {
      return await addContentFn({ ...data }, personalDetails.id);
    } else {
      return await saveAll();
    }
  };
  const addContentFn = async (d, resumeId) => {
    const { sectionOrder } = customization;
    const res = await addContent({ content: d, sectionOrder, resumeId });
    if (res?.code === 200) {
      updateSection(
        produce(content[d.sectionType], (draft) => {
          draft.id = res.data.contentId;
          draft.entries[draft.entries.length - 1].id = res.data.entryId;
        }),
        d.sectionType
      );
      if (res?.code === 401) {
        setShowLogin(true);
        setIsLogin(false);
        return;
      }
      setCurrentTab("content");
      return res;
    }
  };
  const editContentFn = async (d, contentId) => {
    return await editContent({
      ...d,
      id: contentId,
      resumeId: personalDetails.id,
    });
  };
  const editSectionNameFn = async (data: Content) => {
    return await editSectionName({
      id: data.id,
      displayName: data.displayName,
      iconKey: data.iconKey,
    });
  };
  const addEntryFn = async (data, c) => {
    const res = await addEntry({
      ...data,
      order: c.entries.length - 1,
      contentId: c.id,
    });
    if (res?.code === 200) {
      updateSection(
        produce(content[c.sectionType], (draft) => {
          draft.entries[c.entries.length - 1].id = res.data.entryId;
        }),
        c.sectionType
      );
      setCurrentTab("content");
      return res;
    }
  };
  const delEntryFn = async (data, content) => {
    if (content.entries.length <= 1) {
      if (content.id) {
        const res = await delContent({
          id: content.id,
          resumeId: personalDetails.id,
        });
        if (res?.code === 200) {
          deleteContent(content.sectionType);
          setCurrentTab("content");
          return res;
        }
      } else {
        deleteContent(content.sectionType);
        setCurrentTab("content");
      }
    } else {
      if (data.id) {
        const res = await delEntry({ id: data.id, contentId: content.id });
        if (res?.code === 200) {
          updateSection(
            produce(content, (draft) => {
              const index = draft.entries.findIndex(
                (item) => item.id === data.id
              );
              draft.entries.splice(index, 1);
            }) as any,
            content.sectionType
          );
          setCurrentTab("content");
          return res;
        }
      } else {
        let s: any = produce(content, (draft) => {
          const index = draft.entries.findIndex(
            (item) => item.key === data.key
          );
          draft.entries.splice(index, 1);
        });
        updateSection(s, content.sectionType);
        setCurrentTab("content");
      }
    }
  };
  const editEntryFn = async (data) => {
    const res = await editEntry({ ...data });
    if (res?.code === 200) {
      // setCurrentTab("content");
      goback();
      return res;
    }
  };
  const toggleHideEntryFn = async (data) => {
    if (!needLogin()) {
      return {
        code: 200,
      };
    }
    if (personalDetails.id) {
      const res = await toggleHideEntry({ ...data });
      if (res?.code === 200) {
        return res;
      }
    } else {
      return await saveAll();
    }
  };
  const sortEntryFn = async (contentId, newOrder) => {
    if (personalDetails.id) {
      const res = await sortEntry({
        contentId,
        newOrder,
      });
    } else {
      return await saveAll();
    }
  };
  const updatePersonalDetailFn = async (personalDetails) => {
    if (personalDetails.id) {
      const obj = { ...personalDetails };
      for (const i in obj) {
        if (obj[i] == null || obj[i] === "") {
          obj[i] = null;
        }
      }
      const res = await updatePersonalDetail({ ...obj });
      if (res?.code === 200) {
        setCurrentTab("content");
        return res;
      }
    }
  };
  return {
    saveAll,
    save,
    addContentFn,
    editContentFn,
    editSectionNameFn,
    addEntryFn,
    delEntryFn,
    editEntryFn,
    toggleHideEntryFn,
    sortEntryFn,
    updatePersonalDetailFn,
  };
};

export default Index;
